package org.smart4j.framework.helper;

import org.smart4j.framework.annotation.Inject;
import org.smart4j.framework.util.ReflectionUtil;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 依赖注入的助手类
 * @author luoyong
 * @date 2018-11-19下午 7:33
 */
public final class IocHelper {

    //将ioc容器中带有@inject注解的实例对象注入到当前类中(依赖注入)
    static {
        HashMap<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
        if (beanMap != null){
            for (Map.Entry<Class<?>,Object> entry : beanMap.entrySet()){
                Class<?> beanClass = entry.getKey();
                Object beanValue = entry.getValue();
                if (beanClass != null){
                    Field[] declaredFields = beanClass.getDeclaredFields();
                    if (declaredFields != null){
                        for (Field field : declaredFields){
                            if (field.isAnnotationPresent(Inject.class)){
                                Class<?> fieldClass = field.getType();
                                Object beanInstance = BeanHelper.getBean(fieldClass);
                                if (beanInstance != null) {
                                    ReflectionUtil.setField(beanValue, field, beanInstance);
                                }
                            }
                        }
                    }
                }

            }
        }

    }



}
